package wiki;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.Root;


import java.io.*;



/**
 * 
 * @author mona.chandrapal
 */
@MultipartConfig


public class fileupload extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 7389045457989150580L;

	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("application/json");
		//PrintWriter out = response.getWriter();
		
		
		Root root = new Root();
		ResultSet rs = null;
		PreparedStatement pst = null;
		
		
		System.out.println("ProcessRequest !");
		
        String issueid = request.getParameter("issueid");
        System.out.println("Issueid = " + issueid);
        
        
		String description = request.getParameter("description"); // Retrieves <input type="text" name="description">
		    Part filePart = request.getPart("file"); // Retrieves <input type="file" name="file">
		    System.out.println("Description: " + description);
			
		    String filename = getFileName(filePart);
		    System.out.println("filename: " + filename);
		    
		     
		    InputStream filecontent = filePart.getInputStream();
		    // ... (do your job here)
		    
		    OutputStream outputStream = null;
		    
		 // write the inputStream to a FileOutputStream
			outputStream = 
	                    new FileOutputStream(new File("/"+filename));
	 
			int read = 0;
			byte[] bytes = new byte[1024];
	 
			while ((read = filecontent.read(bytes)) != -1) {
				outputStream.write(bytes, 0, read);
			}
	 
			System.out.println("Done!");
			
			
		
		try {

			String sql1;
					
			File image = new File("/"+filename);
			//File image = filecontent;
			System.out.println("File read !");

			// declare FileInputStream object to store binary stream of given
			// image.
			FileInputStream fis;
			fis = new FileInputStream(image);
			System.out.println("File converted !");

			root.initConnection();

			sql1 = "insert into attachedfile(filename, file, issueid) values(?,?,?)";
			pst = root.con.prepareStatement(sql1);
			pst.setString(1, filename);
			pst.setBinaryStream(2, (InputStream) fis, (int) (image.length()));
			pst.setString(3, issueid);
			/*
			 * executeUpdate() method execute specified sql query. Here this
			 * query insert data and image from specified address.
			 */
			int s = pst.executeUpdate();
			if (s > 0) {
				System.out.println("Uploaded successfully !");
				//System.out.println(image);
			} else {
				System.out.println("unsucessfull to upload image.");
			}


		} catch (Exception e) {
			System.out.println("Exception uploading file: " + e.toString());
		} finally {
			try {
				pst.close();
				rs.close();
				root.closeConnection();
			} catch (Exception e) {

			}

	}

		System.out.println("File To DB");
		response.sendRedirect("wiki/viewissue.jsp?issueid=" + issueid);
		

	}
	
	 /**
	    * Utility method to get file name from HTTP header content-disposition
	    */
	   private String getFileName(Part part) {
	       String contentDisp = part.getHeader("content-disposition");
	       System.out.println("content-disposition header= "+contentDisp);
	       String[] tokens = contentDisp.split(";");
	       for (String token : tokens) {
	           if (token.trim().startsWith("filename")) {
	               return token.substring(token.indexOf("=") + 2, token.length()-1);
	           }
	       }
	       return "";
	   }
	   


	   
	

	// <editor-fold defaultstate="collapsed"
	// desc="HttpServlet methods. Click on the + sign on the left to edit the code.">

	/**
	 * Handles the HTTP <code>GET</code> method.
	 * 
	 * @param request
	 *            servlet request
	 * @param response
	 *            servlet response
	 * @throws ServletException
	 *             if a servlet-specific error occurs
	 * @throws IOException
	 *             if an I/O error occurs
	 */
	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * Handles the HTTP <code>POST</code> method.
	 * 
	 * @param request
	 *            servlet request
	 * @param response
	 *            servlet response
	 * @throws ServletException
	 *             if a servlet-specific error occurs
	 * @throws IOException
	 *             if an I/O error occurs
	 */
	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);    
	}
	


	/**
	 * Returns a short description of the servlet.
	 * 
	 * @return a String containing servlet description
	 */
	@Override
	public String getServletInfo() {
		return "Short description";
	}// </editor-fold>
}
